package com.tansuo365.test1.controller.kucunstuff;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tansuo365.test1.bean.kucunbean.ChukuDetails;
import com.tansuo365.test1.bean.kucunbean.ChukuZong;
import com.tansuo365.test1.service.kucunservice.ChukuDetailsService;
import com.tansuo365.test1.service.kucunservice.ChukuZhixingService;
import com.tansuo365.test1.service.kucunservice.ChukuZongService;
import com.tansuo365.test1.service.kucunservice.WuliaoKucunRiZhiService;
import com.tansuo365.test1.service.otherservice.HuishouZhixingService;
import com.tansuo365.test1.util.DateUtil;
import com.tansuo365.test1.util.StringUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@PropertySource(value = "classpath:danhao.properties")
@Api(value = "出库单相关控制层", tags = "", description = "")
@RestController
@RequestMapping("/admin/chukudan")
public class ChukuDanController {

    @Autowired
    private ChukuZongService chukuZongService;
    @Autowired
    private ChukuDetailsService chukuDetailsService;
    @Autowired
    private ChukuZhixingService chukuZhixingService;
    @Autowired
    private HuishouZhixingService huishouZhixingService;
    @Autowired
    private WuliaoKucunRiZhiService wuliaoKucunRiZhiService;

    //    @Autowired
//    private ChukuDetailsService chukuDetailsService;
    @Value("${danhao.chukudan.prefix}")
    private String chukudanPrefix;

    //到货单号生成

    /**
     * 获取申购单号 OK
     *
     * @param type
     * @return
     * @throws Exception
     */
    @Async
    @RequestMapping("/getChukuNumber")
    public ListenableFuture<String> genBillCode(String type) throws Exception {
        StringBuffer billCodeStr = new StringBuffer();
        billCodeStr.append(chukudanPrefix);
        billCodeStr.append(DateUtil.getCurrentDateStr());
        String todayMaxChukuDanNumber = chukuZongService.getTodayMaxChukuDanNumber();
        if (todayMaxChukuDanNumber != null) {
            billCodeStr.append(StringUtil.formatCode(todayMaxChukuDanNumber));
        } else {
            billCodeStr.append("0001");
        }
        return new AsyncResult<>(billCodeStr.toString());
//        return billCodeStr.toString();
    }

    //回收绑定出库单 回填数据
    @RequestMapping("/bangdingChuku")
    public Map<String, Object> getChukudanById(ChukuZong chukuZong) {
        Map<String, Object> resultMap = new HashMap<>();
//        List<ShengouZong> shengouZong1 = shengouZongService.listShengouZong(shengouZong);
//        List<ChukuDetails> chukuDetailsList = chukuDetailsService.listChukuDetailsByZongId(chukuZong.getId());
//        resultMap.put("shengouZong",shengouZong1.get(0));
        //根据出库zong获取出库单的详细中,那些物料,以及那些物料的对应物料表的可回收与否和回收项.
        List<ChukuDetails> chukuDetailsList = chukuDetailsService.listChukuWhereWuliaoKehuishouByZongId(chukuZong.getId());
        resultMap.put("chukuDetailsList", chukuDetailsList);
        resultMap.put("success", true);
        return resultMap;
    }

    @RequestMapping("/getSelective")
    public Map<String, Object> getChukuDan(ChukuZong chukuZong, @RequestParam(value = "page", required = true) Integer page, @RequestParam(value = "rows", required = true) Integer rows) {
        if (chukuZong == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        PageHelper.startPage(page, rows);
        List<ChukuZong> chukuZongsList = chukuZongService.listChukuZong(chukuZong);
        PageInfo<ChukuZong> pageInfo = new PageInfo<>(chukuZongsList);
        resultMap.put("rows", pageInfo.getList());
        resultMap.put("total", pageInfo.getTotal());
        return resultMap;
    }

    /*
    获取出库单 没有完全被退库的数据单子
    如果出库单总表 对应的 出库详细, 与之对应的 退库单 没有完全退完的 才拿回来展示
    整个业务跟申购单,到货单,是属于一个性质.这里需要设定一个出库/退库的统计表,类似申购执行汇总表

    */
    @RequestMapping("/getChukuDanNotFull")
    public Map<String, Object> getChukuDanNotFull(ChukuZong chukuZong, @RequestParam(value = "page", required = true) Integer page, @RequestParam(value = "rows", required = true) Integer rows) {
        System.out.println("getSelective");
        if (chukuZong == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        PageHelper.startPage(page, rows);
        List<ChukuZong> shengouZongsList = chukuZongService.listChukuZongNotAllBack(chukuZong);
        PageInfo<ChukuZong> pageInfo = new PageInfo<ChukuZong>(shengouZongsList);
        resultMap.put("rows", pageInfo.getList());
        resultMap.put("total", pageInfo.getTotal());
        return resultMap;
    }

    @RequestMapping("/getSelectiveHuishou")
    public Map<String, Object> getChukuDanWithHasKehuishou(ChukuZong chukuZong, @RequestParam(value = "page", required = true) Integer page, @RequestParam(value = "rows", required = true) Integer rows) {
        if (chukuZong == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        PageHelper.startPage(page, rows);
        List<ChukuZong> chukuZongsList = chukuZongService.listChukuZongKehuishou(chukuZong);
        PageInfo<ChukuZong> pageInfo = new PageInfo<>(chukuZongsList);
        resultMap.put("rows", pageInfo.getList());
        resultMap.put("total", pageInfo.getTotal());
        return resultMap;
    }

    //用量查询
    @RequestMapping("/yongliangSearch")
    public Map<String, Object> yongliangSearch(ChukuDetails chukuDetails, @RequestParam(value = "page", required = true) Integer page, @RequestParam(value = "rows", required = true) Integer rows) {
        //根据不同项目 / 单位 / 物料类别的id / 用量的开始结束时间 来展示不同的使用物料用量情况
        if (chukuDetails == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        PageHelper.startPage(page, rows);
        List<ChukuDetails> yongliangDetailsList = chukuDetailsService.yongliangSearch(chukuDetails);
        PageInfo<ChukuDetails> pageInfo = new PageInfo<ChukuDetails>(yongliangDetailsList);
        resultMap.put("rows", pageInfo.getList());
        resultMap.put("total", pageInfo.getTotal());
        return resultMap;
    }

    //返回的数据已经是只是未采购和部分采购
    @RequestMapping("/listDetailsByZIdBindCondition")
    public Map<String, Object> listDetailsByZongIdWhichNotFull(@RequestParam("id") Integer id) {
        Map<String, Object> resultMap = new HashMap<>();
//        List<ShengouZong> shengouZong1 = shengouZongService.listShengouZong(shengouZong);
        List<ChukuDetails> chukuDetailsList = chukuDetailsService.listChukuDetailsWithTuikuIfNotAllBack(id);
//        resultMap.put("shengouZong",shengouZong1.get(0));
        resultMap.put("chukuDetailsList", chukuDetailsList);
        resultMap.put("success", true);
        return resultMap;
    }

    @RequestMapping("/listDetailsByZId")
    public Map<String, Object> listDetailsByZongId(ChukuDetails chukuDetails, @RequestParam(value = "page", required = true) Integer page, @RequestParam(value = "rows", required = true) Integer rows) {
        if (chukuDetails == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        PageHelper.startPage(page, rows);
        List<ChukuDetails> chukuDetailsList = chukuDetailsService.listChukuDetailsSelective(chukuDetails);
        PageInfo<ChukuDetails> pageInfo = new PageInfo<>(chukuDetailsList);
        resultMap.put("rows", pageInfo.getList());
        resultMap.put("total", pageInfo.getTotal());
        return resultMap;
    }

    //保存出库单及主表
    @RequestMapping("/save")
    public Map<String, Object> save(HttpSession session, ChukuZong chukuZong, @RequestParam("wuliaoChukuDetailsJson") String wuliaoChukuDetailsJson) {
        if (chukuZong == null || wuliaoChukuDetailsJson == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        Gson gson = new Gson();
        List<ChukuDetails> chukuDetailsList = gson.fromJson(wuliaoChukuDetailsJson, new TypeToken<List<ChukuDetails>>() {
        }.getType());

        chukuZong.setFounder((String) session.getAttribute("truename"));
        //save时, 先保存大表, 大表返回id后再保存附表
        int insertCode = chukuZongService.saveZongAndDetails(chukuZong, chukuDetailsList);
        int i = 0;
        if (insertCode > 0) {
            i = chukuZhixingService.saveChukuToZhixing(chukuDetailsList, chukuZong);
        }
        if (insertCode > 0 && i > 0) {
            resultMap.put("success", true);
            resultMap.put("msg", "保存成功.");
            return resultMap;
        } else if (insertCode == 0) {
            resultMap.put("success", false);
            resultMap.put("errorInfo", "保存失败");
            return resultMap;
        } else if (insertCode < -99) {
            ChukuDetails chukuDetails = chukuDetailsList.get((-insertCode) - 100);
            resultMap.put("success", false);
            resultMap.put("errorInfo", "保存失败,保存出库物料[" + chukuDetails.getMingchengguige() + "]超过现有库存数量,请核对库存数量再进行出库操作.");
            return resultMap;
        } else {
            ChukuDetails chukuDetails = chukuDetailsList.get((-(insertCode) - 1));
            resultMap.put("success", false);
            resultMap.put("errorInfo", "保存失败,保存物料[" + chukuDetails.getMingchengguige() + "]不存在库存中.");
            return resultMap;
        }
    }

    @RequestMapping("/update")
    public Map<String, Object> update(ChukuZong chukuZong) {
        if (chukuZong == null) {
            return null;
        }
        Map<String, Object> resultMap = new HashMap<>();
        int updateCode = chukuZongService.updateByPrimaryKeySelective(chukuZong);
        if (updateCode > 0) {
            resultMap.put("success", true);
            return resultMap;
        } else {
            resultMap.put("success", false);
            return resultMap;
        }
    }

    @RequestMapping("/delete")
    @Transactional
    public Map<String, Object> deleteBatch(@RequestParam("ids[]") Integer[] ids) {
        Map<String, Object> resultMap = new HashMap<>();
        if (ids == null) {
            resultMap.put("success", false);
            resultMap.put("errorInfo", "请选中条目进行删除");
            return resultMap;
        }
        //根据chukudanzongservice获取ids里包含哪些chukudanhao s
        List<String> chukudanhaos = null;
        chukudanhaos = chukuZongService.listChukudanhaos(ids);

        int chukuzhixingCode = 0;
        int huishouzhixingCode = 0;


        int kucunChange = wuliaoKucunRiZhiService.insertButDeleteChukuShu(ids);
        int ziDelCode = 0;
        int code = chukuZongService.deleteBatchByPKArr(ids);  //批量删除chuku主表
        if (code > 0) {
            ziDelCode = chukuDetailsService.deleteByZongIdArr(ids); //批量删除chuku详细根据ids条目
        }
        if(ziDelCode>0){
            //wuliaochukudanmingxihuizong 根据duiying出库单号删除
            chukuzhixingCode = chukuZhixingService.deleteByChukudans(chukudanhaos);
            huishouzhixingCode = huishouZhixingService.deleteByDuiyingChukudans(chukudanhaos);
        }
        //huishouzhixingCode不能判定,yin未出库单不一定都是hui'sho回收的
        //出库单在出库执行中肯定会生成,所以判定chukuzhixingCode
        if (code > 0 && ziDelCode > 0 && chukuzhixingCode > 0 && kucunChange > 0) {
            resultMap.put("success", true);
            return resultMap;
        } else {
            resultMap.put("success", false);
            return resultMap;
        }
    }

}
